package com.cool.apigateway.filter;

import com.cool.common.model.response.ResponseResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class ErrorFilter implements GlobalFilter, Ordered {
    private final ObjectMapper objectMapper;

    public ErrorFilter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return chain.filter(exchange).onErrorResume(throwable -> {
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

            if (throwable instanceof org.springframework.cloud.gateway.support.NotFoundException) {
                response.setStatusCode(HttpStatus.NOT_FOUND);
                return writeErrorResponse(response, "1004", "服务未找到");
            }

            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            return writeErrorResponse(response, "5000", "网关处理请求失败");
        });
    }

    private Mono<Void> writeErrorResponse(ServerHttpResponse response, String code, String message) {
        try {
            ResponseResult<Void> result = ResponseResult.fail(code, message);
            byte[] bytes = objectMapper.writeValueAsBytes(result);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            return Mono.error(e);
        }
    }

    @Override
    public int getOrder() {
        return -1; // 高优先级
    }
}